import { ref, watchEffect } from 'vue'
import { defineStore } from 'pinia'
import type { UserVo } from '@/type/User'
import defaultAvatar from '@/assets/default-avatar.jpg'

// localStorage键名常量
const STORAGE_KEYS = {
  TOKEN: 'auth_token',
  USER_INFO: 'user_info'
}

export const useAuthStore = defineStore('auth', () => {
  // 状态初始化时尝试读取localStorage
  const initialAuth = getLocalStorageData()

  /* token */
  const accessToken = ref<string | null>(initialAuth.token)
  /* 用户信息 */
  const userInfo = ref<{
    username: string | null
    userId: string | null
    nickname: string | null
    avatar: string | null
  }>(initialAuth.userInfo)

  // 自动同步到localStorage的监听
  watchEffect(() => {
    // 同步token
    if (accessToken.value) {
      localStorage.setItem(STORAGE_KEYS.TOKEN, accessToken.value)
    } else {
      localStorage.removeItem(STORAGE_KEYS.TOKEN)
    }
    // 同步用户信息
    if (userInfo.value.username) {
      localStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify(userInfo.value))
    } else {
      localStorage.removeItem(STORAGE_KEYS.USER_INFO)
    }
  })

  function setToken(token: string | null) {
    accessToken.value = token
  }

  function setUserInfo(user: UserVo) {
    userInfo.value = {
      username: user.username,
      userId: user.userId,
      nickname: user.nickname,
      avatar: (user.avatar === null || user.avatar === '')
        ? defaultAvatar
        : user.avatar
    }
  }

  function clearAuth() {
    accessToken.value = null
    userInfo.value = {
      username: null,
      nickname: null,
      avatar: null
    }
    // 确保清除localStorage
    localStorage.removeItem(STORAGE_KEYS.TOKEN)
    localStorage.removeItem(STORAGE_KEYS.USER_INFO)
  }

  return {
    accessToken,
    userInfo,
    setToken,
    setUserInfo,
    clearAuth
  }
})

// 辅助函数：初始化时读取localStorage
function getLocalStorageData() {
  // SSR兼容处理
  if (typeof window === 'undefined') {
    return { token: null, userInfo: null }
  }

  try {
    return {
      token: localStorage.getItem(STORAGE_KEYS.TOKEN),
      userInfo: JSON.parse(localStorage.getItem(STORAGE_KEYS.USER_INFO) || 'null') || {
        username: null,
        nickname: null,
        avatar: null
      }
    }
  } catch (error) {
    console.error('LocalStorage解析失败:', error)
    return { token: null, userInfo: null }
  }
}
